import routes from './routes';
import { routerRedux } from 'dva/router';

class RouterTool {
  static instance = null;

  constructor () {
    this.routeMapper = {};
    // 初始化
    // RouterTool.routeMapper
    const mapper = {};
    routes.forEach((_) => {
      mapper[_.name] = _;
    });

    this.routeMapper = mapper;
  }

  static New () {
    if (RouterTool.instance instanceof RouterTool) {
      return RouterTool.instance;
    }

    RouterTool.instance = new RouterTool();
    return RouterTool.instance;
  }

  getPathByName (name) {
    const router = this.routeMapper[name];
    return router ? router.path : "";
  }

  getRouteByName (name) {
    return this.routeMapper[name];
  }

  redirectTo (args) {
    let _args = null;
    if (typeof args === 'object') {
      const { name, params, ...otherArgs } = args;

      const pathname = this.getPathByName(name);
      const pathnames = [];
      
      pathname.split('/').forEach((_) => {
        if (_.startsWith(':')) {
          const str = params[_.replace(':', '')] || null;
          if (str) {
            pathnames.push(str);
          }
        } else {
          pathnames.push(_);
        }
      });

      const path = pathnames.join('/');

      _args = {
        pathname: path,
        ...otherArgs,
      };
    }
    if (typeof args === 'string') {
      _args = this.getPathByName(args) || args;
    }

    return routerRedux.push(_args);
  }
}

export default RouterTool;

export const routerTool = RouterTool.New();
